package com.md.websocket;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Gong
 * @Description
 * @dATE 2022/4/11 21:48
 **/
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
//@ServerEndpoint(value = "/chat")
public class ChatEndPoint {
    //因为每个客户端都有一个本类对象存在，对每个客户端进行管理
    private static Map<String,ChatEndPoint> onlineUsers = new ConcurrentHashMap<String,ChatEndPoint>();
    //声明session,通过该对象可以发送消息给指定的用户。
    private Session session;
    private HttpSession httpSession;//可以拿到对应的用户信息
    @OnOpen
    public void onOpen(Session session,EndpointConfig config){
        System.out.println("连接调用");
        this.session = session;
        HttpSession httpSession =(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;
        String username = "匿名"+ new Random().nextInt(100);
        if(null != httpSession){
            username = (String)httpSession.getAttribute("username");
        }
        onlineUsers.put(username,this);
        //登录成功后需要进行广播通知
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(new Date());
        broadcastAllUsers(nowTime+"["+username+"]登录成功。");
        //当前在线用户信息
        broadcastAllUsers("在线用户："+onlineUsers.keySet());
    }
    private void broadcastAllUsers(String message){
        //将消息广播给所有的客户端
        Set<String> users = onlineUsers.keySet();

            for (String username : users) {
                try {
                    ChatEndPoint chatEndPoint = onlineUsers.get(username);
                        //发送数据
                    chatEndPoint.session.getBasicRemote().sendText(message);
                    System.out.println("已广播数据"+username);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("用户"+username+"过期，已移除。");
                    onlineUsers.remove(username);
                }
            }

        
    }
    @OnMessage
    //接收到数据时调用
    public void onMessage(String message, Session session){
        System.out.println("接消息调用："+message);
        if(null != this.httpSession){
            String username = (String)httpSession.getAttribute("username");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = sdf.format(new Date());
            broadcastAllUsers(nowTime+"["+username+"]:"+message);
        }else{
            broadcastAllUsers("匿名用户:"+message);
        }

    }

    @OnClose
    public void onClose(Session session){
        System.out.println("关闭调用");
    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("报错调用");
    }
}
